<template>
  <!-- 添加或修改艺人管理对话框 -->
  <el-dialog :title="title" :visible.sync="visible" width="900px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="form" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name" :rules="[{ required: true, message: '请填写姓名' }]">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="照片" prop="avatar" :rules="[{ required: true, message: '请上传照片' }]">
            <div class="text-center">
              <userAvatar :avatar="form.avatar" @imageUrl="getAvatar" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex" :rules="[{ required: true, message: '请填写性别' }]">
            <el-select style="width: 100%" v-model="form.sex" placeholder="请选择性别" clearable>
              <el-option v-for="dict in genderOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标签" prop="labs" :rules="[{ required: true, message: '请选择标签', trigger: 'blur' }]">
            <el-select style="width: 100%" v-model="form.labs" multiple placeholder="请选择标签">
              <el-option v-for="item in labList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生年月" prop="birthday" :rules="[{ required: true, message: '请选择出生年月' }]">
            <el-date-picker v-model="form.birthday" type="date" placeholder="请选择日期" style="width: 100%"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学校" prop="school" :rules="[{ required: true, message: '请填写学校' }]">
            <el-input v-model="form.school"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业" prop="major" :rules="[{ required: true, message: '请填写专业' }]">
            <el-input v-model="form.major"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="民族" prop="famous" :rules="[{ required: true, message: '请填写民族' }]">
            <el-input v-model="form.famous"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身高" prop="height" :rules="[{ required: true, message: '请填写身高' }]">
            <el-input v-model="form.height"> <template slot="append">cm</template></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="体重" prop="weight" :rules="[{ required: true, message: '请填写体重' }]">
            <el-input v-model="form.weight">
              <template slot="append">kg</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="籍贯" prop="hometown" :rules="[{ required: true, message: '请填写籍贯' }]">
            <el-input v-model="form.hometown"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否单身" prop="dog" :rules="[{ required: true, message: '请填写是否单身' }]">
            <el-input v-model="form.dog"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称/外号" prop="nickName" :rules="[{ required: true, message: '请填写昵称/外号' }]">
            <el-input v-model="form.nickName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职业" prop="work" :rules="[{ required: true, message: '请填写职业' }]">
            <el-input v-model="form.work"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone" :rules="[{ required: true, message: '请填写联系方式' }]">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="现居地" prop="address" :rules="[{ required: true, message: '请填写现居地' }]">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="社交平台账号" prop="social" :rules="[{ required: true, message: '请填写社交平台账号' }]">
            <el-input v-model="form.social"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有/无经纪公司" prop="agent" :rules="[{ required: true, message: '请填写' }]">
            <el-input v-model="form.agent"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="MBTI" prop="mbti" :rules="[{ required: true, message: '请填写MBTI' }]">
            <el-input v-model="form.mbti"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <template v-if="!isEditArt && !isEditCand">
        <el-row>
          <el-col :span="12">
            <el-form-item label="添加到项目候选人">
              <el-switch v-model="switched"> </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="switched">
            <el-form-item label="所属项目">
              <el-select style="width: 100%" v-model="projectIds" multiple placeholder="请选择" @change="selectProject">
                <el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-if="!isEditArt">
        <el-tabs v-model="activeName">
          <template v-for="(item, index) in projectList">
            <el-tab-pane v-if="!item.disabled" :label="item.name" :name="index + ''">
              <el-form :ref="'project' + index" :model="item" label-width="140px">
                <el-row :gutter="20">
                  <el-col :span="12" v-for="(keyItem, keyIndex) in item.keys">
                    <el-form-item :label="keyItem.key" :prop="'keys.' + keyIndex + '.value'" :rules="{
                      required: keyItem.require == 'yes',
                      message: '不能为空',
                      trigger: 'blur'
                    }">
                      <el-input @input="$forceUpdate()" v-model="keyItem.value"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </template>
        </el-tabs>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addArtist, updateArtist } from '@/api/system/artist'
import { getProject } from '@/api/system/project'
import { listLab } from '@/api/system/lab'
import userAvatar from '../components/userAvatar'
import upload from '../../candidate/components/Upload.vue'

export default {
  dicts: ['sys_user_sex'],
  props: {
    projectOptions: {
      type: Array,
      default: () => []
    }
  },
  mixins: [],
  components: { userAvatar, upload },
  data() {
    return {
      genderOptions: [
        {
          value: '男',
          label: '男'
        },
        {
          value: '女',
          label: '女'
        }
      ],
      activeName: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      visible: false,
      // 表单参数
      form: {
        avatar: '',
        name: '',
        sex: '',
        birthday: '',
        school: '',
        major: '',
        famous: '',
        height: '',
        weight: '',
        hometown: '',
        dog: '',
        nickName: '',
        work: '',
        phone: '',
        address: '',
        social: '',
        agent: '',
        mbti: '',
        labs: []
      },
      switched: false,
      labOptions: [],
      projectIds: [],
      projectList: [],
      labList: [],
      isEditArt: false,
      isEditCand: false
    }
  },
  computed: {
    // Your computed here
  },
  watch: {
    projectIds: {
      handler(val) {
        if (val && val.length) {
          this.activeName = '0'
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    open(title, formData) {
      this.form = {}
      this.$set(this.form, 'avatar', '')
      this.resetForm('form')
      this.getLabList()
      this.visible = true
      this.form = formData
      this.isEditArt = formData.isEditArt
      this.isEditCand = formData.isEditCand
      this.projectIds = formData.projectIds
      this.switched = this.projectIds && !!this.projectIds.length
      this.title = title
      this.projectList =
        formData?.projectInfoList?.map(p => {
          p.keys = JSON.parse(p.projectInfo) || []
          p.form = {}
          p.keys.forEach(item => {
            this.$set(p.form, item.key, item.value)
            // p.form[item.key] = item.value
          })
          p.name = p.projectName
          return p
        }) || []
    },
    reset() {
      this.projectList = []
      this.switched = false
      this.projectIds = []
      this.form = {
        avatar: '',
        name: '',
        sex: '',
        birthday: '',
        school: '',
        major: '',
        famous: '',
        height: '',
        weight: '',
        hometown: '',
        dog: '',
        nickName: '',
        work: '',
        phone: '',
        address: '',
        social: '',
        agent: '',
        mbti: '',
        labs: []
      }
      this.resetForm('form')
      this.$refs?.form?.clearValidate()
    },
    /** 提交按钮 */
    submitForm() {
      const tempForm = {
        ...this.form,
        projectInfoList: this.projectList
          ? this.projectList.map(item => {
            return {
              projectId: item.projectId,
              projectInfo: JSON.stringify(item.keys),
              disabled: item.disabled
            }
          })
          : []
      }

      if (!this.isEditArt && this.switched) {
        let totalValid = false
        tempForm.projectInfoList.forEach((item, index) => {
          if (!item.disabled) {
            const key = 'project' + index

            this.$refs[key][0].validate(valid => {
              totalValid = valid
            })
          }
        })

        if (!totalValid) {
          this.$modal.msgError('请检查填写字段')
          return false
        }
      }

      this.$refs['form'].validate(valid => {
        if (valid) {
          if (tempForm.id != null) {
            updateArtist(tempForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.visible = false
              this.$emit('update')
              this.reset()
            })
          } else {
            addArtist(tempForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.visible = false
              this.$emit('update')
              this.reset()
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.visible = false
      this.reset()
    },
    async selectProject(e) {
      this.projectList = []
      e.forEach(async id => {
        await this.getProjectDetail(id)
      })

      this.activeName = '0'
    },
    async getProjectDetail(id) {
      const res = await getProject(id)
      res.data.form = {}
      res.data.projectId = res.data.id
      res.data.keys = JSON.parse(res.data.projectInfo) || []
      res.data.keys.forEach(item => {
        res.data.form[item.key] = item.value
      })
      this.projectList.unshift(res.data)
    },
    getLabList() {
      listLab({
        pageNum: 1,
        pageSize: 999
      }).then(response => {
        this.labList = response.rows
      })
    },
    async getAvatar(url) {
      this.form = {
        ...this.form,
        avatar: url
      }
    }
  },
  created() {
    // console.log('Component created');
  },
  mounted() {
    // console.log('Component created');
  }
}
</script>

<style scoped>
/* Your styles here */
</style>
